package com.echo.mockito;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;

import java.util.Random;

public class DemoTest2 {

    // mock对象，对函数的调用均使用mock，不会调用真实方法
    @Mock
    private Random random;

    // spy对象，对函数的调用是真实调用
    @Spy
    private Demo demo;

    @BeforeEach
    void before() {
        System.out.println("-------- 测试前准备 --------");
        // 激活Mockito相关注解
        MockitoAnnotations.openMocks(this);
    }

    @AfterEach
    void after() {
        System.out.println("-------- 测试结束 --------");
    }

    @Test
    public void test1() {
        Mockito.when(random.nextInt()).thenReturn(100);
        System.out.println(random.nextInt());
        Assertions.assertEquals(100, random.nextInt());
    }

    @Test
    public void test2() {
        /*{
            // 方法真实调用
            System.out.println(demo.add(1, 2));
        }*/
        /*{
            // 打桩，返回指定值
            Mockito.when(demo.add(1, 2)).thenReturn(0);
            System.out.println(demo.add(1, 2));
            // Assertions.assertEquals(3, demo.add(1, 2));
            Assertions.assertEquals(0, demo.add(1, 2));
        }*/
        /*{
            // 方法调用时抛出异常
            Mockito.when(demo.add(1, 2)).thenThrow(new RuntimeException());
            demo.add(1, 2);
        }*/
        {
            // 监控真实对象
            Mockito.when(demo.add(1, 2)).thenCallRealMethod();
            Assertions.assertEquals(3, demo.add(1, 2));
        }
    }
}
